package com.zhss.concurrency.shcolumn;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

/**
 * @ClassName chapter01
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/8/5 16:32
 * @Version 1.0
 */
public class chapter01 {
	public static void main(String[] args) {
//		final Count count = new Count();

		//单线程的方式统计访问次数
//		IntStream.range(0, 1000).forEach(i -> count.countAdd());
		// 多线程统计访问次数
//		IntStream.range(0,1000).parallel().forEach(i->count.countAdd());
		// 多线程使用原子类统计并发访问次数
//		System.out.println(count.getCount());

//		AtomicIntegerCount atomicIntegerCount = new AtomicIntegerCount();

//		SynCount count = new SynCount();

		LockCount count = new LockCount();
		IntStream.range(0, 1000).parallel().forEach(i -> count.countAdd());



//		System.out.println(atomicIntegerCount.getCount());
		System.out.println(count.getCount());
	}
}
class Count{

	public int getCount() {
		return count;
	}
	private int count = 0;

	public void countAdd() {
		count++;
	}
}

class AtomicIntegerCount{

	public int getCount() {
		return count.get();
	}

	private AtomicInteger count = new AtomicInteger(0);

	public void countAdd() {
		count.incrementAndGet();
	}
}

class SynCount {

	public int getCount() {
		return count;
	}

	private int count;

	public synchronized void countAdd() {
		count++;
	}
}

class LockCount {

	public int getCount() {
		return count;
	}

	private ReentrantLock lock = new ReentrantLock();
	private int count;

	public void countAdd() {
		lock.lock();
		count++;
		lock.unlock();
	}
}
